package cn.cstech.aijia.appupgrade;

import android.app.Dialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.widget.RemoteViews;


import java.io.File;

import cn.cstech.aijia.R;
import cn.cstech.aijia.ui.base.utils.DialogUtil;
import cn.cstech.aijia.BaseApplication;
import cn.cstech.aijia.common.DirConstants;
import cn.cstech.aijia.ui.MainActivity;
import cn.cstech.aijia.ui.base.utils.LoadingDialog;
import cn.cstech.aijia.ui.base.utils.LocalUtils;
import cn.cstech.aijia.ui.base.utils.NetworkUtil;
import cn.cstech.aijia.ui.base.utils.SPUtils;

/**
 * Created by sky on 14-3-27.
 *
 * App升级管理类
 */
public class AppUpdateManager {
    public static final String UPDATE_LEVEL = "update_level";
    public static final String UPDATE_DESC = "update_desc";
    public static final String DOWNLOAD_URL = "download_url";
    public static final String APP_VERSION = "app_version";
    public static final int UPDATE_NORMAL = 1;
    public static final int UPDATE_FORCE = 2;
    private static final String TAG = "test";
    private boolean mUserManualCheck = false;
    public enum UpdateStatus {
        IDLE,
        CHECKING,
        DOWNLOADING
    }

//    private static AppUpdateManager sharedInstance = null;
    private Context mContext;
    private AppUpdateInfo mUpdateInfo;
    private UpdateStatus mUpdateStatus = UpdateStatus.IDLE;
    private String mApkName = "papd.apk";
    private LoadingDialog mProgressDialog;
    
    private Handler mHandler ;
    public AppUpdateManager(Handler handler){
    	mHandler = handler;
    }
    
    public AppUpdateManager(Context context){
    	mContext = context;
    }

//    public static AppUpdateManager sharedInstance(Handler handler) {
//        if (sharedInstance == null) {
//            sharedInstance = new AppUpdateManager(handler);
//        }
//        return sharedInstance;
//    }

    public void checkUpdate(Context context, boolean userManualCheck) {
    	if(!NetworkUtil.isNetworkAvailable(context)){
    		LocalUtils.showToast(context, R.string.network_unavailable);
    		return ;
    	}
    	mUserManualCheck = userManualCheck;
        mContext = context;
        getUpdateData();

    }

    private void getUpdateData() {
        if (mUpdateStatus != UpdateStatus.IDLE) {
            return;
        }
        mUpdateStatus = UpdateStatus.CHECKING;
        if (mUserManualCheck) {
        	showProgressDialog();
        }
        doGetUpdateData();
    }

    public static final int MSG_HAS_UPDATE = 0x1005;
    public static final int MSG_UPDATE_APP = 0x1006;
    public static final int MSG_HIDE_UPATE_DLG = 0x1007;
//    public static final int MSG_SHOW_PROGRESS_DLG = 0x1108;
    private void doGetUpdateData() {
//    	NetManager.getInstance(mContext).checkAppUpdate("pajk", new OnCheckAppUpdateListener() {
//
//			@Override
//			public void onComplete(boolean isOK, AppUpdateInfo upgradeInfo,
//					int errorCode, String errorMsg) {
//				if(isOK){
//					if(upgradeInfo != null){
//						mUpdateInfo = upgradeInfo;
//						Preference.save(mContext, Preference.APP_LATEST_VER,(int)mUpdateInfo.getVersion());
//
//						boolean needUpdate = checkNeedUpdate(mContext);
//				        if (needUpdate) {
//				            registerBroadcast();
//				            Message.obtain(mHandler, MSG_HAS_UPDATE).sendToTarget();
//				        } else {
//				            mUpdateStatus = UpdateStatus.IDLE;
//				            if(mUserManualCheck){
//				            	Message.obtain(mHandler, MSG_HIDE_UPATE_DLG, mContext.getString(R.string.toast_no_update)).sendToTarget();
//				            }
//				        }
//					}else{
//						mUpdateStatus = UpdateStatus.IDLE;
//						if(mHandler != null && mUserManualCheck){
//							Message.obtain(mHandler, MSG_HIDE_UPATE_DLG, mContext.getString(R.string.toast_no_update)).sendToTarget();
//						}
//					}
//				}else{
//					mUpdateStatus = UpdateStatus.IDLE;
//					if(mHandler != null && mUserManualCheck){
//						Message.obtain(mHandler, MSG_HIDE_UPATE_DLG, mContext.getString(R.string.toast_net_error)).sendToTarget();
//					}
//				}
//			}
//
//			@Override
//			public void onInernError(int errorCode, String errorMessage) {
//				mUpdateStatus = UpdateStatus.IDLE;
//				if(mHandler != null && mUserManualCheck){
//					Message.obtain(mHandler, MSG_HIDE_UPATE_DLG, errorMessage).sendToTarget();
//				}
//			}
//		});
    }
    public void showProgressDialog() {
    	if(mProgressDialog == null){
    		mProgressDialog = DialogUtil.showLoadingDialog(mContext, mContext.getString(R.string.dlg_msg_app_check_update), true);
//    		mProgressDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
    	}
    	mProgressDialog.show();
    }

    public void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
    Dialog updateDialog;
    public void showUpdateInfoDialog(Context context) {
        final boolean updateLevel = mUpdateInfo.isForceUpgrade();
        String desc = mUpdateInfo.getDesc();

        if(updateDialog == null){
        	if(mUpdateInfo.isForceUpgrade()){
        		updateDialog = DialogUtil.showMessageDialog(context,
        				context.getString(R.string.dlg_title_hint),
        				desc,
        				context.getString(R.string.force_update),  
    	        		null,
    	        		new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								((BaseApplication)mContext.getApplicationContext()).exitAllActivity();
								
								if(LocalUtils.isSDCardMounted()){
									mUpdateStatus = UpdateStatus.DOWNLOADING;
	    			                startDownloadService();
								}else{
									mUpdateStatus = UpdateStatus.IDLE;
									LocalUtils.showToast(mContext, R.string.sdcard_unavailable);
								}
    			                updateDialog.dismiss();
							}
    	                },null);
        		
        	}else{
        		updateDialog = DialogUtil.showMessageDialog(context,
                        context.getString(R.string.dlg_title_hint),
                        desc,
                        context.getString(R.string.update_next_time),
                        context.getString(R.string.update_now),
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mUpdateStatus = UpdateStatus.IDLE;
                                unregisterBroadcast();
                                updateDialog.dismiss();
                            }
                        },
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (LocalUtils.isSDCardMounted()) {
                                    mUpdateStatus = UpdateStatus.DOWNLOADING;
                                    startDownloadService();
                                } else {
                                    mUpdateStatus = UpdateStatus.IDLE;
                                    LocalUtils.showToast(mContext, R.string.sdcard_unavailable);
                                }
                                updateDialog.dismiss();
                            }
                        });
        	}
        }
        updateDialog.setCancelable(false);
        updateDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				if(mUpdateStatus == UpdateStatus.CHECKING){
					mUpdateStatus = UpdateStatus.IDLE;
				}
			}
		});
//        dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        updateDialog.show();
    }
    boolean isRegister = false;
    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadService.ACTION_DOWNLOAD_FINISH);
        filter.addAction(DownloadService.ACTION_DOWNLOAD_FAILED);
//      filter.addAction(DownloadService.ACTION_DOWNLOAD_PUBLISH_PROGRESS);
//      LocalBroadcastManager.getInstance(mContext).registerReceiver(mReceiver, filter);
        mContext.registerReceiver(mReceiver, filter);
        
        isRegister = true;
    }

    private void unregisterBroadcast() {
//      LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
        try {
            if (isRegister) {
                mContext.unregisterReceiver(mReceiver);

                isRegister = false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean checkNeedUpdate(Context context) {
        int currentVersion = LocalUtils.getAppVersionCode(context);
        int serverVersion = 0;
        try{
            serverVersion = SPUtils.getInt(context, SPUtils.APP_LATEST_VER);
            if(serverVersion <= currentVersion) {
                return false;
            }

            return shouldNotifyUser(context);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    public boolean isNeedUpdate(){
    	return checkNeedUpdate(mContext);
    }

    //userManualCheck 是否用户主动触发检测更新，如果是则忽略1天时间
    private boolean shouldNotifyUser(Context context) {
//        if (mUserManualCheck) {
//            return true;
//        }
//
//        long timeDesc = Preference.getLong(context, Preference.APP_REJECT_UPDATE_TIME);
//        if (timeDesc == 0) {
//            return true;
//        }
//
//        long currentTime = System.currentTimeMillis();
//        return currentTime > timeDesc + 1 * 24 * 60 * 60 * 1000;
    	return true;
    }

    private void startDownloadService() {
        String url = mUpdateInfo.getDownloadUrl();
        Intent intent = new Intent(mContext, DownloadService.class);
        intent.setAction(DownloadService.ACTION_DOWNLOAD);
        intent.putExtra(DownloadService.DOWNLOAD_URL, url);
        intent.putExtra(DownloadService.SAVE_PATH, DirConstants.DIR_UPDATE_APP + mApkName);
        intent.putExtra(DownloadService.SAVE_IN_EXTERNAL, true);
        intent.putExtra(DownloadService.SHOW_NOTIFICATION, true);
        intent.putExtra(DownloadService.DOWNLOAD_PROGRESS_NOTIFICATION, getDownloadProgressNotification());
        intent.putExtra(DownloadService.DOWNLOAD_FINISH_NOTIFICATION, getDownloadFinishNotification());
        intent.putExtra(DownloadService.DOWNLOAD_FAIL_NOTIFICATION, getDownloadFailNotification());
        intent.putExtra(DownloadService.PROGRESSBAR_ID, R.id.barProgress);
        intent.putExtra(DownloadService.TEXTVIEW_ID, R.id.txtProgress);
        mContext.startService(intent);
    }

    private Notification getDownloadProgressNotification() {
        RemoteViews view = new RemoteViews(mContext.getPackageName(),
                R.layout.notification_downloading);
        view.setTextViewText(R.id.txtName, mContext.getText(R.string.app_name));
        view.setImageViewResource(R.id.imgIcon,
                android.R.drawable.stat_sys_download);
        view.setProgressBar(R.id.barProgress, 100, 0, true);
        view.setTextViewText(R.id.txtProgress, "0%");

        Notification notification = new Notification(android.R.drawable.stat_sys_download,
                "下载中",
                System.currentTimeMillis());
        notification.icon = android.R.drawable.stat_sys_download;
        notification.flags = Notification.FLAG_NO_CLEAR;

        Intent notificationIntent = new Intent(mContext, MainActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, 0);
        notification.contentView = view;
        notification.contentIntent = contentIntent;
        return notification;
    }

    private Notification getDownloadFinishNotification() {
        PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, getInstallIntent(mApkName), 0);
        Notification notification = new Notification(
                android.R.drawable.stat_sys_download_done,
                "下载完成",
                System.currentTimeMillis());
        notification.setLatestEventInfo(mContext,
                mContext.getString(R.string.app_name),
                "下载完成", pIntent);
        notification.contentIntent = pIntent;
        notification.flags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_NO_CLEAR;
        return notification;
    }

    private Notification getDownloadFailNotification() {
        PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, new Intent(), 0);
        Notification notification = new Notification(
                android.R.drawable.stat_sys_warning,
                "下载失败",
                System.currentTimeMillis());
        notification.setLatestEventInfo(mContext,
                mContext.getString(R.string.app_name),
                "下载失败", pIntent);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        return notification;
    }

    private Intent getInstallIntent(String fileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.fromFile(new File(mContext.getFilesDir().getPath() + "/" + fileName)),
                "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    private void doInstall(String fileName) {
        mContext.startActivity(getInstallIntent(fileName));
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            /*if (action.equals(DownloadService.ACTION_DOWNLOAD_PUBLISH_PROGRESS)) {

            } else */
            if (action.equals(DownloadService.ACTION_DOWNLOAD_FINISH)) {
                mUpdateStatus = UpdateStatus.IDLE;
//                doInstall(mApkName);
                unregisterBroadcast();
            } else if (action.equals(DownloadService.ACTION_DOWNLOAD_FAILED)) {
                mUpdateStatus = UpdateStatus.IDLE;
                unregisterBroadcast();
            }
        }
    };

    public interface AppUpdateCheckListener {
        public void onStatusUpdate(UpdateStatus status);
        public void onForceUpdate();
    }
}
